<!-- 地点编辑 -->
<template>
  <div class='page-container'>
    <ex_super_form ref="formRef" v-bind="formModel" label-position="right" label-width="140px"
      style="overflow-y: auto;">

    </ex_super_form>
    <div style="margin-left: 140px; margin-bottom: 20px;">
      <el-button type="primary" @click="submitForm()">{{ $tt('label_confirm') }}</el-button>
      <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
    </div>
    <MapContainer ref="aMapRef" :autoComplete="searchMap" @position="getPosition" isClick />
  </div>
</template>
<script>
// 代码中有使用 countryCode==='CN'做判断
// 如果中国的countryCode被修改
// 切换城市地图中心将不会变化
// 国外经纬度非必填 切换城市地图中心将不会变化
import MapContainer from '@/component/common/MapContainer.vue'
import router_params from '@/mixin/router_params';
export default {
  name: 'title_place_manage',
  mixins: [router_params],
  components: { MapContainer },
  data() {
    return {
      // 省份
      provinceList: [],
      // 城市
      cityList: [],
      // 区
      countyList: [],
      formModel: {
        itemClass: "form_item_default",
        inputClass: "form_input_default",
        formClass: "flex_row_wrap",
        default: {},
        model: [
          { key: 'addressName', label: 'label_place_name' },
          { key: 'addressAbb', label: 'label_place_abb' },
          { key: 'basePlaceTypeEnum', label: 'label_place_type', type: 'select', enum: "BasePlaceTypeEnum" },
          {
            key: 'countryCode',
            label: 'label_country',
            filterable: true,
            type: 'select',
            storeData: true,
            url: '/tms-api/client/TmsPlaceInfoClientRpc/selectCountry.json',
            on: {
              changeItem: (data) => {
                // 国外 经纬度非必填
                this.formModel.rules.longitude[0].required = data.countryNameEn === 'China'
                this.formModel.rules.latitude[0].required = data.countryNameEn === 'China'
                // 联动数据清空
                this.clearFromData(['province', 'city', 'county'])
                //获取省份数据
                this.getAddressLabelDTO({ countryCode: data.countryCode }, 'provinceList')
                this.cityList = []
                this.countyList = []
              },
            },
            ref: 'testRef',
            option: { label: 'labelStr', value: 'countryCode' },
            keyExtra: { countryName: 'countryName', countryCode: 'countryCode' }
          },
          {
            key: 'province',
            label: 'label_province',
            render: (h, { data }) => {
              return <el-select
                class='form_input_default'
                filterable
                value={data.province}
                onChange={value => {
                  this.$set(data, 'province', value)
                  // 联动数据清空
                  this.clearFromData(['city', 'county'])
                  //获取城市数据
                  this.getAddressLabelDTO({ countryCode: data.countryCode, provDistCd: value }, 'cityList')
                  this.countyList = []
                }}
                placeholder={this.$t('tip_please_select')}>
                {this.provinceList.map((item, index) => <el-option key={index} label={item.address} value={item.address} />)}
              </el-select>
            },
          },
          {

            key: 'city',
            label: 'label_city',
            render: (h, { data }) => {
              return <el-select
                filterable
                class='form_input_default'
                value={data.city}
                onChange={value => {
                  this.$set(data, 'city', value)

                  // 城市为叶子节点时 县区非必填
                  const item = this.cityList.find(item => value === item.address)
                  this.formModel.rules.county.required = item.isLeaf !== 'Y'

                  // 联动数据清空
                  this.clearFromData(['county'])
                  //获取区数据
                  this.getAddressLabelDTO({ countryCode: data.countryCode, provDistCd: data.province, cityDistCd: data.city }, 'countyList')

                  if (data.countryCode === 'CN' && this.$refs.aMapRef && this.$refs.aMapRef.map) {
                    this.$refs.aMapRef.map.setCity(value)
                  }

                }}
                placeholder={this.$t('tip_please_select')}>
                {this.cityList.map((item, index) => <el-option key={index} label={item.address} value={item.address} />)}
              </el-select>
            },
          },
          {

            key: 'county',
            label: 'label_county',
            render: (h, { data }) => {
              return <el-select
                filterable
                class='form_input_default'
                value={data.county}
                onChange={value => {
                  this.$set(data, 'county', value)

                }}
                placeholder={this.$t('tip_please_select')}>
                {this.countyList.map((item, index) => <el-option key={index} label={item.address} value={item.address} />)}
              </el-select>
            },
          },
          { key: 'longitude', label: 'label_lon' },
          { key: 'latitude', label: 'label_lat' },
          {
            key: 'addressDetail', label: 'label_detail_address',
            render: (h, { data }) => {
              return <el-input
                id="tipinput"
                class='form_input_default'
                type="textarea"
                autosize={{ minRows: 2, maxRows: 4 }}
                value={data.addressDetail}
                onInput={value => {
                  this.$set(data, 'addressDetail', value)
                }}
                onChange={value => {
                  this.$set(data, 'addressDetail', value)
                }}
              />
            }
          },
          { key: 'postalCode', label: 'label_post_code' },
          { key: 'contacts', label: 'label_contact' },
          { key: 'contactNumber', label: 'label_contact_phone' },

        ],
        rules: {
          addressName: { required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },
          addressAbb: { required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' },
          basePlaceTypeEnum: { required: true, message: this.$t('tip_can_no_empty'), trigger: 'change' },
          countryCode: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          province: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          city: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          county: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          addressDetail: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          postalCode: { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
          longitude: [
            { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
            { pattern: /^-?((0|[1-9]\d?|1[0-7]\d)(\.\d{1,6})?|180(\.0{1,6})?)$/, message: this.$t('label_lonreg_msg') }
          ],
          latitude: [
            { required: true, message: this.$t('tip_can_no_empty'), trigger: ['blur', 'change'] },
            { pattern: /^-?((0|[1-8]\d?)(\.\d{1,6})?|90(\.0{1,6})?)$/, message: this.$t('label_latreg_msg'), trigger: 'blur' }
          ],

        },
      },
      MapAutoComplete: null,
      address: ''
    }
  },

  methods: {
    init_data_default(params) {
      if (params.edit) this.edit = params.edit
      if (this.edit) {
        if (params.id) {
          this.loading = true
          this.$ajax({
            url: "/oms-api/base/OmsBaseClientAddressRpc/detail.json",
            method: 'get',
            data: { id: params.id },
            success: async (res) => {
              this.loading = false
              // 国外 经纬度非必填
              this.formModel.rules.longitude[0].required = res.data.countryCode === 'CN'
              this.formModel.rules.latitude[0].required = res.data.countryCode === 'CN'

              this.$refs.formRef.setData(res.data)
              if (res.data.longitude && res.data.latitude) {
                setTimeout(() => {
                  this.$refs.aMapRef.setMarker([res.data.longitude, res.data.latitude])
                  try {
                    this.$refs.aMapRef.map.setCenter([res.data.longitude, res.data.latitude])
                  } catch (error) {
                    this.$message.error('请检查经纬度是否正确')
                  }
                }, 1000);
              }

              //获取省份数据
              if (res.data.countryCode) {
                await this.getAddressLabelDTO({ countryCode: res.data.countryCode }, 'provinceList')
              }
              //获取城市数据
              if (res.data.countryCode && res.data.province) {
                await this.getAddressLabelDTO({ countryCode: res.data.countryCode, provDistCd: res.data.province }, 'cityList')

                // 城市为叶子节点时 县区非必填
                if (res.data.city) {
                  const item = this.cityList.find(item => res.data.city === item.address)
                  console.log(this.provinceList, res.data.city)
                  this.formModel.rules.county.required = item.isLeaf !== 'Y'
                }
              }
              //获取区数据
              if (res.data.countryCode && res.data.province && res.data.city) {
                await this.getAddressLabelDTO({ countryCode: res.data.countryCode, provDistCd: res.data.province, cityDistCd: res.data.city }, 'countyList')
              }
              this.$emit("tagModifyLabel", { _key: 'title_edit_place', code: res.data.addressName || "" })

            }
          })
        }

        this.$emit("tagModifyLabel", { _key: 'title_edit_place', code: this.$t("tip_loading") })

      } else {
        this.$emit('tagModifyLabel', "title_create_place")
      }
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.MapAutoComplete = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      // 当选中某条搜索记录时触发
      this.MapAutoComplete.on("select", this.$refs.aMapRef.selectSite);
    },
    // 通过地图获取信息
    async getPosition(position) {
      if (position) {
        // 用来判断是否修改省市， 如果没变化不需要重新获取省市数据
        const oldFormData = JSON.parse(JSON.stringify(this.$refs.formRef.getData()))
        // 获取具体地址
        const address = `${position.province}${position.city}${position.county}`
        position.addressDetail = position.addressDetail.substring(address.length, position.addressDetail.length)

        // 遍历设置表单数据
        Object.keys(position).forEach(key => {
          this.$refs.formRef.set(key, position[key])
        })
        // 通过地图获取的数据 默认会是中国
        this.$refs.formRef.set('countryCode', 'CN')

        // 获取各行政区的下拉数据
        const formData = this.$refs.formRef.getData()

        //获取省份数据
        if (formData.countryCode !== oldFormData.countryCode) {
          await this.getAddressLabelDTO({ countryCode: 'CN' }, 'provinceList')
        }
        //获取城市数据
        if (formData.province !== oldFormData.province) {
          await this.getAddressLabelDTO({ countryCode: formData.countryCode, provDistCd: formData.province }, 'cityList')
        }
        //获取区数据
        if (formData.city !== oldFormData.city) {
          await this.getAddressLabelDTO({ countryCode: formData.countryCode, provDistCd: formData.province, cityDistCd: formData.city }, 'countyList')
        }
      }
    },
    // 获取省份、城市、区
    getAddressLabelDTO(params, key) {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: "/tms-api/client/TmsPlaceInfoClientRpc/selectAddressLabelDTO.json",
          method: 'post',
          data: params,
          success: ({ data: { rows } }) => {
            this[key] = rows
            resolve(rows)
          }
        })
      })

    },
    // 联动数据清空
    clearFromData(keys) {
      const formData = this.$refs.formRef.getData()
      keys.forEach(key => {
        if (formData[key]) {
          this.$refs.formRef.set(key, '')
        }
      })
    },
    submitForm() {
      this.$refs['formRef'].validate((valid, obj) => {
        if (valid) {
          this.$ajax({
            url: "/oms-api/base/OmsBaseClientAddressRpc/edit.json",
            method: 'post',
            type: 'json',
            loading: this.$tt('tip_submiting'),
            data: this.$refs.formRef.getFormData(),
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.$emitPage('oms>place_manage', 'reload')
              this.return_page_back()
            }
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });

    },
  }
}
</script>
<style scoped lang='less'>
#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 540px;
  margin: 0;
}
</style>
